package com.edu.niit.newsapp.util;

import android.util.Log;
import com.edu.niit.newsapp.config.SystemConfig;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by annie on 2016/9/17.
 */
public class HttpUtil {

    public static void httpGetData_Get(final String surl){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                try {
                    //创建URL对象
                    URL url = new URL(surl);
                    //返回一个URLConnection对象，它表示到URL所引用的远程对象链接
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    //请求所需要的apikey
                    httpURLConnection.setRequestProperty("apikey", SystemConfig.BAIDU_APIKEY);
                    //设定请求方法，默认是GET方法
                    httpURLConnection.setRequestMethod("GET");
                    //设置连接超时时间
                    httpURLConnection.setConnectTimeout(10000);
                    //设置读取数据超时时间
                    httpURLConnection.setReadTimeout(5000);
                    //获取响应状态码
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        //定义一个输入流，获取服务器返回的数据
                        InputStream is = httpURLConnection.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        //逐行遍历
                        String request = "";
                        String response = "";
                        while ((request = br.readLine()) != null) {
                            response += request;
                            Log.d("=======>>>>>>>>>", response);
                        }
                        br.close();
                        isr.close();
                        is.close();
                    }
                } catch (MalformedURLException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                } finally {
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }
}
